package net.zjitc.demosecurity6.filter;


import com.alibaba.fastjson.JSON;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import net.zjitc.demosecurity6.pojo.LoginUser;
import net.zjitc.demosecurity6.utils.JwtUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * @Author zhao
 * @DATE 2025/4/25 15:54
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

       //如果是login 放行放行
        if (request.getRequestURI().equals("/login")){
            filterChain.doFilter(request,response);
            return;
        }
        String token = request.getHeader("Jwt");
        // 如果token为空，则直接放行
        if (token == null) {
            throw new RuntimeException("token为空");
        }
        //解析Token
        if (JwtUtil.isTokenExpired(token)){
            throw new RuntimeException("token已过期");
        }
        String subject = JwtUtil.getSubjectFromToken(token);
        //将字符串转为对象
        LoginUser loginUser = JSON.parseObject(subject, LoginUser.class);

        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        filterChain.doFilter(request,response);

    }


}
